package cn.com.headfree.xxk.service.impl;

import cn.com.headfree.drafts.service.IDraftsService;
import cn.com.headfree.entity.*;
import cn.com.headfree.userinfo.service.IUserInfoService;
import cn.com.headfree.util.SysDictionaryUtil;
import cn.com.headfree.util.ZipGenerateUtils;
import cn.com.headfree.vo.CommonVo;
import cn.com.headfree.vo.TEmpBaseInfoVo;
import cn.com.headfree.vo.complex.*;
import cn.com.headfree.xxk.dao.IMessageCardDao;
import cn.com.headfree.xxk.service.IMessageCardService;
import cn.com.headfree.xxk.vo.DsdtVo;
import cn.com.headfree.xxk.vo.UserVo;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.common.dto.ResultData;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

//import net.sf.jxls.transformer.XLSTransformer;

@Service("/messageCardService")
public class MessageCardServiceImpl implements IMessageCardService {
	private static final Logger LOG = LogManager.getLogger(MessageCardServiceImpl.class);

	@Autowired
	public IUserInfoService userInfoService;

	@Autowired
	private IDraftsService draftsService;
	@Autowired
	public IMessageCardDao messageCardDao;

	// 临时下载路径
	@Value("${file_temp_path}")
	private String file_temp_path;

//	public static final String separator = File.separator;

	@Override
	public ResultData messagCardExport( HttpServletRequest request, HttpServletResponse response,
			String erpNos, String deptId, String deptName) {
		ResultData rs = new ResultData();
		try {
			if (!StringUtil.isNullOrEmpty(erpNos)) {
				if (erpNos.contains(",")) {
					List<File> files = new ArrayList<File>();
					String erpNoArray[] = erpNos.split(",");
					for (String erpNo : erpNoArray) {
						TEmpBaseInfoVo user=userInfoService.getNowBaseInfoByErpNo(erpNo);
						if(user!=null) {
							File file=this.exportMessageCard(user, request, response, erpNo, deptId, deptName);
							files.add(file);
						}
					}
					ZipGenerateUtils.ZipFiles(request, response, files, deptName+"-青年人才信息卡.rar");
					deleteDirectory(file_temp_path);
				} else {
					TEmpBaseInfoVo user=userInfoService.getNowBaseInfoByErpNo(erpNos);
					if(user!=null) {
						File file=this.exportMessageCard(user, request, response, erpNos, deptId, deptName);
						this.downloadSingleFile(request,response,file,user);
					}
				}
			}else {
				//根据deptId获取该部门下的人员信息
				List<UserVo> users=messageCardDao.getUsersByDeptId(deptId);
				if(users!=null&&users.size()>0) {
					List<File> files = new ArrayList<File>();
					for(cn.com.headfree.xxk.vo.UserVo UserVo :users) {
						TEmpBaseInfoVo user=userInfoService.getNowBaseInfoByErpNo(UserVo.getErpNo());
						if(user!=null) {
							File file=this.exportMessageCard(user, request, response, UserVo.getErpNo(), deptId, deptName);
							files.add(file);
						}
					}
					ZipGenerateUtils.ZipFiles(request, response, files, deptName+"-青年人才信息卡.rar");
					deleteDirectory(file_temp_path);
				}
			}
			rs.setData("青年人才信息卡导出成功！");
		} catch (Exception e) {
			rs.setSuccess(false);
			rs.setErrorMsg("青年人才信息卡导出异常！");
			LOG.error("青年人才信息卡导出异常！", e);
		}
		return rs;
	}

	private void downloadSingleFile(HttpServletRequest request, HttpServletResponse response, File file, TEmpBaseInfoVo user) {
		ByteArrayOutputStream os = null;
		FileInputStream fis = null;
		try {
			os = new ByteArrayOutputStream();
			fis=new FileInputStream(file);
			int data = -1;
	        while ((data = fis.read()) != -1) {
	            os.write(data);
	        }
			response.reset();
//	        String fileName = user.getName()+"-青年人才信息卡.xlsx";
	        String fileName = user.getName()+"-青年人才信息卡.xls";
			fileName = URLEncoder.encode(fileName, "UTF8").replaceAll("\\+", "%20");// 其他浏览器
			response.addHeader("Content-Disposition",
					"attachment;filename=" + fileName);
			response.addHeader("Content-Length", "" + os.size());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(os.toByteArray());
			toClient.flush();
			toClient.close();
			fis.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据erpNo导出相关用户的青年人才信息卡
	 * 
	 * @param response
	 * @param erpNo
	 * @param deptId
	 * @param deptName
	 */
	private File exportMessageCard(TEmpBaseInfoVo user, HttpServletRequest request, HttpServletResponse response, String erpNo,
                                   String deptId, String deptName) {
		try {
			// 定义表格使用的数据
			Map<String, Object> data = new HashMap<String, Object>();

			// 获取姓名、所在部门、填卡日期
			data.put("user", user);

			// 填卡日期（当天时间）
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			String addTime = sdf.format(new Date());
			data.put("addTime", addTime);

			List<TPartRank> pr=new ArrayList<TPartRank>();
			TPartRank t=new TPartRank();
			t.setErpNo(erpNo);
			pr.add(t);
			
			// 一、基本信息
			TEmpBaseInfoVo jbxx = userInfoService.getNowBaseInfoByErpNo(erpNo);
			CommonVo zj = draftsService.getGrowthTreeZyzjByErpNo(erpNo);// 获取职员职级
			CommonVo zw = draftsService.getGrowthTreeZwByErpNo(erpNo);// 获取职务
			if (jbxx != null && zj != null) {
				jbxx.setPosZhiName(zj.getValue());
			}
			if (jbxx != null && zw != null) {
				jbxx.setPosName(zw.getValue());
			}
			data.put("jbxx", jbxx);// 放入表数据

			// 查询就业学历最新值
			TEducateInfo jyxl = messageCardDao.getEduceteInfoByJyxl(erpNo);
			if (jyxl != null) {
				jyxl.setSchoolTypeName(
						SysDictionaryUtil.getNameByValueForDefault("CollegeCategory", jyxl.getSchoolType()));
				jyxl.setEducNameName(
						SysDictionaryUtil.getNameByValueForDefault("PersonnelQualifications", jyxl.getEducName()));
				jyxl.setDegreeNameName(
						SysDictionaryUtil.getNameByValueForDefault("AcademicDegree", jyxl.getDegreeName()));
			}
			data.put("jyxl", jyxl);

			// 查询最高学历最新值
			TEducateInfo zgxl = messageCardDao.getEduceteInfoByZgxl(erpNo);
			if (zgxl != null) {
				zgxl.setSchoolTypeName(
						SysDictionaryUtil.getNameByValueForDefault("CollegeCategory", zgxl.getSchoolType()));
				zgxl.setEducNameName(
						SysDictionaryUtil.getNameByValueForDefault("PersonnelQualifications", zgxl.getEducName()));
				zgxl.setDegreeNameName(
						SysDictionaryUtil.getNameByValueForDefault("AcademicDegree", zgxl.getDegreeName()));
			}
			data.put("zgxl", zgxl);

			// 获取技术职称(技能等级信息)
			TSkillLevelInfo skill = messageCardDao.getTSkillLevelInfoByErpNo(erpNo);
			if (skill != null) {
				skill.setTechTypeName(
						SysDictionaryUtil.getNameByValueForDefault("SkillAppraisalWork", skill.getTechType()));
				skill.setQualifiLevelName(
						SysDictionaryUtil.getNameByValueForDefault("QualificationLevel", skill.getQualifiLevel()));
				skill.setOrgLevelName(
						SysDictionaryUtil.getNameByValueForDefault("IdentificationUnitLevel", skill.getOrgLevel()));
			}
			data.put("skill", skill);

			// 获取职级名称（专业技术资格）
			TProTecInfo proTecInfo = messageCardDao.getTProTecInfoByErpNo(erpNo);
			if(proTecInfo!=null) {
				proTecInfo.setSubjSetName(SysDictionaryUtil.getNameByValueForDefault("ProTechnicalQualifications", proTecInfo.getSubjSet()));
				proTecInfo.setSubjLevelName(SysDictionaryUtil.getNameByValueForDefault("ProfessionalQualifications", proTecInfo.getSubjLevel()));
				proTecInfo.setOrgLevelName(SysDictionaryUtil.getNameByValueForDefault("IdentificationUnitLevel", proTecInfo.getOrgLevel()));
			}
			data.put("proTecInfo", proTecInfo);

			// 二、工作履历
			Page<TWorkExpInfo> page1 = new Page<TWorkExpInfo>();
			page1.setPageNo(1);
			page1.setPageSize(1000);
			TWorkExpInfo tWorkExpInfo = new TWorkExpInfo();
			tWorkExpInfo.setErpNo(erpNo);
			userInfoService.findPageWorkExpInfoByCondi(page1, tWorkExpInfo);
			List<TWorkExpInfo> gzll = page1.getResult();
			data.put("gzll", gzll);// 放入表数据

			// 三、学历信息
			Page<TEducateInfo> page2 = new Page<TEducateInfo>();
			page1.setPageNo(1);
			page1.setPageSize(1000);
			TEducateInfo educateInfo = new TEducateInfo();
			educateInfo.setErpNo(erpNo);
			userInfoService.findPageEducateInfoByCondi(page2, educateInfo);
			if (!page2.getResult().isEmpty()) {
				page2.getResult().forEach(p -> {
					p.setSchoolTypeName(
							SysDictionaryUtil.getNameByValueForDefault("CollegeCategory", p.getSchoolType()));
					p.setEducNameName(
							SysDictionaryUtil.getNameByValueForDefault("PersonnelQualifications", p.getEducName()));
					p.setDegreeNameName(
							SysDictionaryUtil.getNameByValueForDefault("AcademicDegree", p.getDegreeName()));
				});
			}
			List<TEducateInfo> xlxx = page2.getResult();
			data.put("xlxx", xlxx);// 放入表数据

			// 四、培训信息
			TContiStudyInfo tContiStudyInfo = new TContiStudyInfo();
			tContiStudyInfo.setErpNo(erpNo);
			Page<TContiStudyInfo> page3 = new Page<TContiStudyInfo>();
			page3.setPageNo(1);
			page3.setPageSize(1000);
			userInfoService.findPageContiStudyInfoByCondi(page3, tContiStudyInfo);
			if (!page3.getResult().isEmpty()) {
				page3.getResult().forEach(p -> {
					p.setTypeName(SysDictionaryUtil.getNameByValueForDefault("PeixunshoukeType", p.getType()));// 绩效等级
					SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
					p.setStartTimeStr(sd.format(p.getStartTime()));
					p.setEndTimeStr(sd.format(p.getEndTime()));
				});
			}
			List<TContiStudyInfo> pxxx = page3.getResult();
			data.put("pxxx", pxxx);// 放入表数据

			// 五、家庭信息

			// 六、奖励信息
			// （一）成果获奖
			// 1,获取科技管理及创新成果
			TTecManInnov tTecManInnov = new TTecManInnov();
			tTecManInnov.setErpNo(erpNo);
			Page<TTecManInnovVo> page4 = new Page<TTecManInnovVo>();
			page4.setPageNo(1);
			page4.setPageSize(1000);
			tTecManInnov.settPartRankList(pr);
			userInfoService.findPageTecManInnovByCondi(page4, tTecManInnov);
			if (!page4.getResult().isEmpty()) {
				page4.getResult().forEach(p -> {
					p.setRoleName(SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoJs", p.getRole()));
					p.setAwardLevelName(SysDictionaryUtil.getNameByValueForDefault("JygexinQcJb", p.getAwardLevel()));
					p.setAwardGradeName(SysDictionaryUtil.getNameByValueForDefault("JygexinQcDj", p.getAwardGrade()));
					p.setAchiTypeName(SysDictionaryUtil.getNameByValueForDefault("KjglAchiveType", p.getAchiType()));
				});
			}
			List<TTecManInnovVo> kjglcx = page4.getResult();
			data.put("kjglcx", kjglcx);// 放入表数据
			// 2，获取项目课题成果
			TProjAchieveInfo tProjAchieveInfo = new TProjAchieveInfo();
			tProjAchieveInfo.setErpNo(erpNo);
			Page<TProjAchieveInfoVo> page8 = new Page<TProjAchieveInfoVo>();
			page8.setPageNo(1);
			page8.setPageSize(1000);
			tProjAchieveInfo.settPartRankList(pr);
			userInfoService.findPageProjAchieveInfoByCondi(page8, tProjAchieveInfo);
			if (!page8.getResult().isEmpty()) {
				page8.getResult().forEach(p -> {
					p.setRoleName(SysDictionaryUtil.getNameByValueForDefault("XiangMuKeTiJS", p.getRole()));
					p.setProjLevelName(SysDictionaryUtil.getNameByValueForDefault("StandardLevel", p.getProjLevel()));
					SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
					p.setStartDateStr(sd.format(p.getStartDate()));
					p.setEndDateStr(sd.format(p.getEndDate()));
				});
			}
			List<TProjAchieveInfoVo> xmktcg = page8.getResult();
			data.put("xmktcg", xmktcg);// 放入表数据

			// （二）个人荣誉
			THonorInfo tHonorInfo = new THonorInfo();
			tHonorInfo.setErpNo(erpNo);
			Page<THonorInfo> page5 = new Page<THonorInfo>();
			page5.setPageNo(1);
			page5.setPageSize(1000);
			userInfoService.findPageHonorInfoByCondi(page5, tHonorInfo);
			if (!page5.getResult().isEmpty()) {
				page5.getResult().forEach(p -> {
					p.setHonorLevelName(SysDictionaryUtil.getNameByValueForDefault("JygexinQcJb", p.getHonorLevel()));
					p.setHonorTypeName(SysDictionaryUtil.getNameByValueForDefault("RuYuLeiBie", p.getHonorType()));
				});
			}
			List<THonorInfo> grry = page5.getResult();
			data.put("grry", grry);// 放入表数据

			// 七、工作业绩及重大成果
			// （一）论文与著作(学术成果)
			TAcadeAchiveInfo tAcadeAchiveInfo = new TAcadeAchiveInfo();
			tAcadeAchiveInfo.setErpNo(erpNo);
			Page<TAcadeAchiveInfoVo> page9 = new Page<TAcadeAchiveInfoVo>();
			page9.setPageNo(1);
			page9.setPageSize(1000);
			
			tAcadeAchiveInfo.settPartRankList(pr);
			
			userInfoService.findPageAcadeAchiveInfoByCondi(page9, tAcadeAchiveInfo);
			if (!page9.getResult().isEmpty()) {
				page9.getResult().forEach(p -> {
					p.setRoleName(SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoJs", p.getRole()));
					p.setAcadTypeName(
							SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoType", p.getAcadType()));
					p.setLevelName(SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoJb", p.getLevel()));
				});
			}
			List<TAcadeAchiveInfoVo> lwzz = page9.getResult();
			data.put("lwzz", lwzz);// 放入表数据

			// （二）制度标准（标准规程、制度方案）
			TStandInfo tStandInfo = new TStandInfo();
			tStandInfo.setErpNo(erpNo);
			Page<TStandInfoVo> page6 = new Page<TStandInfoVo>();
			page6.setPageNo(1);
			page6.setPageSize(1000);
			
			tStandInfo.settPartRankList(pr);
			
			userInfoService.findPageStandInfoByCondi(page6, tStandInfo);
			if (!page6.getResult().isEmpty()) {
				page6.getResult().forEach(p -> {
					p.setRoleName(SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoJs", p.getRole()));
					p.setTypeName(SysDictionaryUtil.getNameByValueForDefault("ZdbzType", p.getType()));
					p.setLevelName(SysDictionaryUtil.getNameByValueForDefault("JygexinQcJb", p.getLevel()));
				});
			}
			List<TStandInfoVo> bzgc = page6.getResult();
			data.put("bzgc", bzgc);// 放入表数据

			// （三）技艺革新（各类专利及QC成果）
			TTecInnovInfo tTecInnovInfo = new TTecInnovInfo();
			tTecInnovInfo.setErpNo(erpNo);
			Page<TTecInnovInfoVo> page7 = new Page<TTecInnovInfoVo>();
			page7.setPageNo(1);
			page7.setPageSize(1000);
			tTecInnovInfo.settPartRankList(pr);
			userInfoService.findPageTecInnovInfoByCondi(page7, tTecInnovInfo);
			if (!page7.getResult().isEmpty()) {
				page7.getResult().forEach(p -> {
					p.setRoleName(SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoJs", p.getRole()));
					p.setAwardLevelName(SysDictionaryUtil.getNameByValueForDefault("JygexinQcJb", p.getAwardLevel()));
					p.setAwardGradeName(SysDictionaryUtil.getNameByValueForDefault("JygexinQcDj", p.getAwardGrade()));
				});
			}
			List<TTecInnovInfoVo> jygx = page7.getResult();
			data.put("jygx", jygx);// 放入表数据

			// 专利、软件著作权
			TPatentInfo tPatentInfo = new TPatentInfo();
			tPatentInfo.setErpNo(erpNo);
			Page<TPatentInfoVo> pageTPatentInfo = new Page<TPatentInfoVo>();
			pageTPatentInfo.setPageNo(1);
			pageTPatentInfo.setPageSize(1000);
			tPatentInfo.settPartRankList(pr);
			userInfoService.findPagePatentInfoByCondi(pageTPatentInfo, tPatentInfo);
			if (!pageTPatentInfo.getResult().isEmpty()) {
				pageTPatentInfo.getResult().forEach(p -> {
					p.setRoleName(SysDictionaryUtil.getNameByValueForDefault("XueshuchengguoJs", p.getRole()));
					p.setPatentTypeName(SysDictionaryUtil.getNameByValueForDefault("PatentType", p.getPatentType()));
				});
			}
			List<TPatentInfoVo> rjzz = pageTPatentInfo.getResult();
			data.put("rjzz", rjzz);// 放入表数据

			// 八、人才培养

			// （一）培训开发
			/*List<TContiStudyInfo> pxkf = messageCardDao.findContiStudyInfoByCondisByErpNo(erpNo, "01");
			if (pxkf != null && pxkf.size() > 0) {
				for (TContiStudyInfo con : pxkf) {
					SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
					con.setStartTimeStr(sd.format(con.getStartTime()));
					con.setEndTimeStr(sd.format(con.getEndTime()));
				}
			}
			data.put("pxkf", pxkf);// 放入表数据
			// （二）授课任务
			List<TContiStudyInfo> skrw = messageCardDao.findContiStudyInfoByCondisByErpNo(erpNo, "02");
			if (skrw != null && skrw.size() > 0) {
				for (TContiStudyInfo con : skrw) {
					SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
					con.setStartTimeStr(sd.format(con.getStartTime()));
					con.setEndTimeStr(sd.format(con.getEndTime()));
				}
			}
			data.put("skrw", skrw);// 放入表数据*/

			// （三）导师带徒
			TSdtTutorPrentInfo tSdtTutorPrentInfo = new TSdtTutorPrentInfo();
			tSdtTutorPrentInfo.setErpNo(erpNo);
			Page<TSdtTutorPrentInfo> page10 = new Page<TSdtTutorPrentInfo>();
			page10.setPageNo(1);
			page10.setPageSize(1000);
			userInfoService.findPageSdtTutorPrentInfoByCondi(page10, tSdtTutorPrentInfo);
			List<TSdtTutorPrentInfo> res = page10.getResult();
			List<DsdtVo> dsdt = new ArrayList<DsdtVo>();
			if (res != null && res.size() > 0) {
				for (TSdtTutorPrentInfo entity : res) {
					// 徒弟所获奖项
					List<TSdtPrentInfo> tSdtPrentInfo = entity.gettSdtPrentInfo();
					for (TSdtPrentInfo e : tSdtPrentInfo) {
						DsdtVo en = new DsdtVo();
						en.setStartTime(entity.getStartDate());
						en.setEndTime(entity.getEndDate());
						en.setContent(entity.getTeachSummary());
						en.setTdName(e.getUserName());
						en.setResult(e.getAwardName());
						dsdt.add(en);	
					}
				}
			}
			data.put("dsdt", dsdt);// 放入表数据

			// 九、组织及参与活动情况

			// 十、个人职业生涯规划

//            // 循环数据
//            List<Object> list = new ArrayList<>();
//            // 表数据
//            for (int i = 1; i <= 5; i++) {
//                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
//                map.put("name", "测试项目" + i);
//                map.put("worNum", i);
//                map.put("comNum", 10);
//                map.put("oil", 5);
//                map.put("gas", (int) (Math.random() * 200));
//                map.put("oilGas", (int) (Math.random() * 200));
//                map.put("oilWater", (int) (Math.random() * 200));
//                map.put("gasWater", (int) (Math.random() * 200));
//                map.put("heavyOil", (int) (Math.random() * 200));
//                map.put("oum", (int) (Math.random() * 200));
//                map.put("success", (49 + i) + "%");
//                map.put("num", (int) (Math.random() * 200));
//                list.add(map);
//            }

			// 设置jxls相关信息
			Context context = new Context();
			for (String key : data.keySet()) {
				context.putVar(key, data.get(key));
			}
			// 获取模板文件
//			File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "templates/qnrcxxk_template.xls");
			
//			InputStream inputStream = new FileInputStream(file);
			ClassPathResource resource=new ClassPathResource("templates/qnrcxxk_template.xls");
			InputStream inputStream=resource.getInputStream();
			// 生成导出文件
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			JxlsHelper.getInstance().processTemplate(inputStream, os, context);

//			XlsCommentAreaBuilder.addCommandMapping("merge", MergeCommand.class);
			
			// 测试-将表格导入本地文件
			FileOutputStream fileOutputStream = null;
			try {
				File fi = new File(file_temp_path);
				if (!fi.exists()) {
					fi.mkdirs();
				}
//				String fileName=file_temp_path+separator+user.getName().replace("*","")+"("+user.getErpNo()+")"+"-青年人才信息卡.xls";
				String fileName=file_temp_path+"//"+user.getName().replace("*","")+"("+user.getErpNo()+")"+"-青年人才信息卡.xls";
				File mkFile=new File(fileName);
				if(!mkFile.exists()) {
					mkFile.createNewFile();
				}
				fileOutputStream = new FileOutputStream(fileName);
				fileOutputStream.write(os.toByteArray());
//				List<File> files = new ArrayList<File>();
				File f=new File(fileName);
				return f;
//				ZipGenerateUtils.ZipFiles(request, response, files, user.getDeptName()+"-青年人才信息卡.rar");
//				deleteDirectory(file_temp_path);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

//			response.reset();
//			response.addHeader("Content-Disposition",
//					"attachment;filename=" + new String(("青年人才信息卡.xlsx").getBytes("UTF-8"), "ISO-8859-1"));
//			response.addHeader("Content-Length", "" + os.size());
//			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//			response.setContentType("application/octet-stream");
//			toClient.write(os.toByteArray());
//			toClient.flush();
//			toClient.close();

//            // 获取模板文件
//            File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "templates/qnrcxxk_template.xls");
//            InputStream inputStream = new FileInputStream(file);
//            // 获取 Workbook ，传入 模板 和 数据 这里是读取的模板
//            XLSTransformer xlsTransformer = new XLSTransformer();
//            Workbook workbook = xlsTransformer.transformXLS(inputStream, data);
//            // 设置文件名
//            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("青年人才信息卡.xls", "UTF-8"));
//            // 写出文件
//            OutputStream os = new BufferedOutputStream(response.getOutputStream());
//            // 输出
//            workbook.write(os);
//            // 关闭
//            inputStream.close();
//            //刷新

		} catch (Exception e) {
			e.printStackTrace();
		}
return null;
	}
	
	/**
	 * 删除目录（文件夹）以及目录下的文件
	 * 
	 * @param sPath 被删除目录的文件路径
	 * @return 目录删除成功返回true，否则返回false
	 */
	public boolean deleteDirectory(String sPath) {
		// 如果sPath不以文件分隔符结尾，自动添加文件分隔符
		if (!sPath.endsWith(File.separator)) {
			sPath = sPath + File.separator;
		}
		File dirFile = new File(sPath);
		// 如果dir对应的文件不存在，或者不是一个目录，则退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return false;
		}
		boolean flag = true;
		// 删除文件夹下的所有文件(包括子目录)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 删除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag)
					break;
			} // 删除子目录
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag)
					break;
			}
		}
		if (!flag)
			return false;
		// 删除当前目录
		if (dirFile.delete()) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 删除单个文件
	 * 
	 * @param sPath 被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	public boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

}
